package pigshare.profilepicture;

import java.io.IOException;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.apache.myfaces.custom.fileupload.UploadedFile;

import pigshare.beans.LoginBean;
import pigshare.database.DatabaseConnection;


import com.mysql.jdbc.Blob;

@ManagedBean
@RequestScoped
public class UpdateProfilePictureBean {

	private UploadedFile uploadedFile;
	public Blob blob;
	private String cookieValue;
	
	private Logger log = Logger.getLogger(LoginBean.class);

	public void submit() throws IOException {
		String fileName = FilenameUtils.getName(uploadedFile.getName());
		String contentType = uploadedFile.getContentType();
		byte[] bytes = uploadedFile.getBytes();
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		Cookie[] cookies = httpServletRequest.getCookies();

		if (cookies != null) {
			for (int j = 0; j < cookies.length; j++) {
				if (cookies[j].getName().equalsIgnoreCase("id")) {
					cookieValue = cookies[j].getValue();
				}
			}
		}

		DatabaseConnection con = new DatabaseConnection();
		try {
			java.sql.PreparedStatement pre = con.getConnection()
					.prepareStatement("UPDATE user SET pic = ? WHERE id = ?");
			pre.setBytes(1, bytes);
			pre.setInt(2, Integer.parseInt(cookieValue));
			pre.executeUpdate();
			pre.close();
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage("Neues Profilbild",String.format(
							"Du hast die Datei '%s' jetzt als neues Profilbild!",
							fileName)));
			log.info(String.format("user with the id " + cookieValue + "  has uploaded a new profilepicture ('%s').",fileName));
		} catch (SQLException e) {
			e.printStackTrace();
		}


	}
	
	public UploadedFile getUploadedFile() {
		return uploadedFile;
	}

	public void setUploadedFile(UploadedFile uploadedFile) {
		this.uploadedFile = uploadedFile;
	}

}
